﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using iOSRemoteConnector;
using System.IO;

using System.Collections.ObjectModel;
using MediaSurfaceV2.MediaConsumerServiceReference;
using System.Collections;


namespace MediaSurfaceV2
{
    /// <summary>
    /// Interaction logic for SurfaceWindow1.xaml
    /// </summary>
    public partial class SurfaceWindow1 : SurfaceWindow
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// 
        private ObservableCollection<mediaConsumerListing> mediaLibraryList;
        static LibraryBar LibraryContent;

        public SurfaceWindow1()
        {

            string[] names = new string[5];
            InitializeComponent();

            //ImageBrush imbg = new ImageBrush();
            //imbg.ImageSource = new BitmapImage(new Uri(@"http://dl.dropbox.com/u/1495186/mss.jpg"));
            //scatterView1.Background = imbg;
            //System.Threading.Thread.Sleep(5000);

            mediaLibraryList = new ObservableCollection<mediaConsumerListing>();
            InitializeSearchOption();

            // Add handlers for Application activation events
            

            mediaElem.MediaEnded += new RoutedEventHandler(mediaEl_MediaEnded);
            mediaElem.LoadedBehavior = System.Windows.Controls.MediaState.Manual;
            mediaElem.Source = new Uri(@"C:\Users\admin\Desktop\MediaSurfaceV2\Underwater.wmv");
            mediaElem.Play();
            iOSRemoteConnector.Program.Main(names);

            AddActivationHandlers();
        }

        public void InitializeSearchOption()
        {
            SearchUserControl sControl = new SearchUserControl();

            libraryBarSuper.Content = sControl;

            LibraryContent = sControl.libraryBar2;

        }



        /// <summary>
        /// Occurs when the window is about to close. 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);

            // Remove handlers for Application activation events
            RemoveActivationHandlers();
        }

        /// <summary>
        /// Adds handlers for Application activation events.
        /// </summary>
        private void AddActivationHandlers()
        {
            // Subscribe to surface application activation events
            ApplicationLauncher.ApplicationActivated += OnApplicationActivated;
            ApplicationLauncher.ApplicationPreviewed += OnApplicationPreviewed;
            ApplicationLauncher.ApplicationDeactivated += OnApplicationDeactivated;
        }

        /// <summary>
        /// Removes handlers for Application activation events.
        /// </summary>
        private void RemoveActivationHandlers()
        {
            // Unsubscribe from surface application activation events
            ApplicationLauncher.ApplicationActivated -= OnApplicationActivated;
            ApplicationLauncher.ApplicationPreviewed -= OnApplicationPreviewed;
            ApplicationLauncher.ApplicationDeactivated -= OnApplicationDeactivated;
        }

        /// <summary>
        /// This is called when application has been activated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationActivated(object sender, EventArgs e)
        {
            //TODO: enable audio, animations here
        }

        /// <summary>
        /// This is called when application is in preview mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationPreviewed(object sender, EventArgs e)
        {
            //TODO: Disable audio here if it is enabled

            //TODO: optionally enable animations here
        }

        /// <summary>
        ///  This is called when application has been deactivated.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApplicationDeactivated(object sender, EventArgs e)
        {
            //TODO: disable audio, animations here
        }

        void mediaEl_MediaEnded(object sender, RoutedEventArgs e)
        {
            MediaElement backgroundVideo = (MediaElement)sender;
            backgroundVideo.Stop();
            backgroundVideo.Play();
        }

        private void TagVisualizer_VisualizationAdded(object sender, TagVisualizerEventArgs e)
        {
            Console.Out.WriteLine("dropped iPhone 4");
            SurfaceBridge sb = new SurfaceBridge();

            //Chris's iPhone
            iOSDevice dev = Devices.GetDevice("a0377f45a9caa08e42a902928a6f9adb1361604e");

            //Teddy's iPhone
            //iOSDevice dev = Devices.GetDevice("db3d69d0b58fd067719bc5fbfe188372b1afd23e");

            //Zabed's iPhone
            //iOSDevice dev = Devices.GetDevice("793da33aa0c9b3f3133db2c183a84afd3a1f239e");


            iOSDevice.OnVideoReceivedDelegate videoDelegate = delegate(MemoryStream filename)
            {

                AddVideoToScatterView(filename);



            };

            dev.onVideoReceivedDelegate = videoDelegate; 




            sb.IOSDevicePlacedDown(1); 





          
        }

        private void AddVideoToScatterView(MemoryStream VideoFile)
        {

            //ScatterViewItem vidScat = new ScatterViewItem();
            //scatterView1.Items.Add(vidScat);

            //MediaElement video = new MediaElement();

            //// Video will play on load.
            //video.LoadedBehavior = MediaState.Play;
            //video.UnloadedBehavior = MediaState.Manual;

            //// The media dimensions are not available until the MediaOpened event.
            //video.MediaOpened += delegate
            //{
            //    // Size the ScatterViewItem control according to the video size.
            //    vidScat.Height = video.NaturalVideoHeight;
            //    vidScat.Width = video.NaturalVideoWidth;
            //};

            //Random a = new Random();
            //Double myDouble = a.NextDouble();


            //FileStream fs = File.OpenWrite(myDouble.ToString()+".mp4");
            //VideoFile.WriteTo(fs);
            //fs.Close();

            //video.MediaFailed += delegate
            //{
            //    vidScat.Content = "Unable to play the video";
            //};

            //// Set ScatterViewItem.Content to the video.
            //vidScat.Content = video;
            
            //// Load and play the video.
            //video.Source = new Uri(@"C:\Users\admin\Desktop\MediaSurfaceV2\MediaSurfaceV2\bin\Debug\" + myDouble.ToString() + ".mp4");
            ScatterViewItem a = new ScatterViewItem();
            DraggedItemControl draggedControl = new DraggedItemControl(VideoFile);
            a.MinHeight = draggedControl.Height;
            a.MinWidth = draggedControl.Width;
            a.Content = draggedControl;
            a.Style = Resources["ControlInScatterViewItemContentStyle"] as Style;
			a.CanScale = false;
            scatterView1.Items.Add(a);
        }

        private void scatterView1_Drop(object sender, SurfaceDragDropEventArgs e)
        {
           

            if (e.Cursor.Data.GetType() == typeof(Image))
            {
                Image test = new Image();
                test = e.Cursor.Data as Image;

                SurfaceBridge sb = new SurfaceBridge();

                sb.RequestFullMovie(1, test.Name);
            }

            else if (e.Cursor.Data.GetType() == typeof(mediaConsumerListing))
            {

                ScatterViewItem newItem = new ScatterViewItem { MinWidth = 430, MinHeight = 330 };
            
                
                mediaConsumerListing listingItem = e.Cursor.Data as mediaConsumerListing;

                if (listingItem.aspect_ratio == 2)
                {
                    newItem.MinWidth = 430;
                    newItem.MinHeight = 330;
                }
                else
                {
                    newItem.MinWidth = 430;
                    newItem.MinHeight = 400;
                }
                
                newItem.Center = e.Cursor.GetPosition(scatterView1);
               
                int removedValue = LibraryContent.Items.IndexOf(listingItem);
           
                MediaConsumerClient client = new MediaConsumerClient();
                String title = listingItem.title;
                int id = listingItem.id;
                requestMediaStruct result = client.requestMedia(id, 3);
                string[] movieTags = listingItem.tags;
           
                SurfaceUserControl1 uControl =
                    new SurfaceUserControl1(scatterView1, newItem, LibraryContent, removedValue, 
                    listingItem.id, listingItem.title.ToString(), listingItem.length.ToString(), 
                    listingItem.pool.ToString(), listingItem.aspect_ratio.ToString(),listingItem.thumbnailUrl, listingItem.description, movieTags);
              
                uControl.SetMediaUrl(result.url); 
                newItem.Content = uControl;
            	newItem.CanScale = true;
                newItem.Center = new Point(460, 250);
                newItem.Style = Resources["ControlInScatterViewItemContentStyle"] as Style;
				scatterView1.Items.Add(newItem);
            }
        }
    }
}